
import { View, Text, Image, Button } from '@tarojs/components'
import styles from "./index.module.scss";
import "./index.scss";
import Taro from "@tarojs/taro";
import { AtFloatLayout } from 'taro-ui'
import { AtButton, AtList, AtListItem, AtProgress, AtCountdown } from 'taro-ui'
import React, { Fragment } from 'react';
import { BaseComponents, Layout ,JoinDialog,WinDialog} from "@/components";
import { lotteryDetailApi, lotteryJoinApi ,lotteryUserListApi} from '@/api/detail';

import rule from "@/images/treasureDetail/icon_rule.png"
import joined from "@/images/treasureDetail/img_seal_joined.png"
import wait from "@/images/treasureDetail/img_seal_wait.png"
import end from "@/images/treasureDetail/img_seal_end.png"
import img_arc from "@/images/treasureDetail/img_arc.png"
import rice from "@/images/home/icon_rice.png"
import icon_right from "@/images/common/icon_right.png"
import icon_left from "@/images/common/icon_left.png"
import icon_close from "@/images/common/icon_close.png"



interface Props { }
interface State {
  lotteryDetail: any;
  baseInfo: any;
  isOpened:boolean;
  isLottery:boolean;
  winDialog: boolean;
  loadding:boolean;
  loadingButton:boolean;
  index: number;
  lotteryUserList:any[];
}

export default class Index extends BaseComponents<Props, State> {

  constructor(props: Props) {
    super(props);

    this.state = {
      lotteryDetail: {},
      baseInfo: {},
      isOpened:false,
      isLottery:false,
      loadding:false,
      winDialog:false,
      loadingButton:false,
      index: 0,
      lotteryUserList:[]
    };
  }

  componentWillMount() { }

  componentDidMount() {
    this.getDetail();
    this.setState({ loadding: true });
    this.getLotteryUserList();
  }

  componentWillUnmount() { }

  componentDidShow() {

  }

  componentDidHide() { }

  //下拉时触发的函数
  onPullDownRefresh() {
    let pages = Taro.getCurrentPages();;
    let currPage: any = null;
    if (pages.length) {
      currPage = pages[pages.length - 1];
    };
    currPage.onShow();
    Taro.stopPullDownRefresh();
  }

  getDetail=()=>{
    const code = Taro.getCurrentInstance().router.params.code;
    const userInfo = Taro.getStorageSync("userInfo");
    lotteryDetailApi(code, userInfo.code).then((res: any) => {
      this.setState({ loadding: false });
      res.lottery.percent = res.lottery.currentCredits / res.lottery.totalCredits;
      res.lottery.openTime = res.lottery.openTime.split(":").splice(0,2).join(":");
      this.setState({ lotteryDetail: res, baseInfo: res.lottery });
      if (res.userJoinStatus==1&&(res.userStatus == 1 || res.userStatus == 2)) {
        this.setState({ isLottery: true })
      }
      if (res.userJoinStatus == 1 && (res.userStatus == 2)) {
        this.setState({ winDialog: true })
      }
    });
  }

  getLotteryUserList = () => {
    const code = Taro.getCurrentInstance().router.params.code;
    lotteryUserListApi(1, 10, code).then((res: any) => {
      this.setState({ lotteryUserList: res.records });
    })
  }

  join=()=>{
    const lotteryCode = Taro.getCurrentInstance().router.params.code;
    const userInfo = Taro.getStorageSync("userInfo");
    this.setState({loadingButton:true});

    lotteryJoinApi({lotteryCode,userCode: userInfo.code}).then((res: any) => {
      this.setState({loadingButton:false});
      if(res){
          this.setState({isOpened:true});
          this.getDetail();
          this.getLotteryUserList();
      }
    });
  }

  goLotteryUserList=()=>{
    const lotteryCode = Taro.getCurrentInstance().router.params.code;
    Taro.navigateTo({ url: `/pages/lotteryUserList/index?code=${lotteryCode}` });
  }

  goAdsWebView=(webUrl)=>{
    Taro.navigateTo({
      url: `/pages/webView/index?webUrl=${webUrl}`
    })
  }

  handleClose() {
    this.setState({ isLottery: false })
  }

  // userJoinStatus 0未参加 1已参加
  //userStatus  待开奖： 0,未中奖： 1, 中奖: 2

  render() {
    const { lotteryDetail, baseInfo,isOpened,isLottery,index,loadding,lotteryUserList,winDialog,loadingButton} = this.state;
    const getAds=Taro.getStorageSync("getAds")?Taro.getStorageSync("getAds"):[]
    return (
      <Layout navBar title="抽奖详情" visibleIcon loadding={loadding}>
        <View className={styles.index} style={{"paddingBottom":lotteryDetail.userJoinStatus==1?"0px":"74px"}}>
          <View className={styles.banner}>
            <Image src={baseInfo.bannerImg ? baseInfo.bannerImg : ""}mode="aspectFit"></Image>
            {lotteryDetail.userJoinStatus == 1 &&<Image src={joined} className={styles.treasureStatus}></Image>}
            {/* {lotteryDetail.userJoinStatus == 1 &&<Image src={wait} className={styles.treasureStatus}></Image>} */}
            {lotteryDetail.userStatus != 0 &&<Image src={end} className={styles.treasureStatus}></Image>}

            <View className={styles.rule} onClick={() => { Taro.navigateTo({ url: '/pages/rule/lotteryRule/index' }) }}>
              <Text>抽奖规则</Text>
              <Image src={rule}></Image>
            </View>
            {lotteryUserList.length > 0 && <View className={styles.announce} onClick={()=>this.goLotteryUserList()}>
              <Image src={lotteryUserList[0].avatar}></Image>
              <View>{lotteryUserList[0].alias}  参与{lotteryUserList[0].credits}积分</View>
              <Text>刚刚</Text>
            </View>}
          </View>

          <View className={styles.openAward}>
            <Text>{baseInfo.openTime} 自动开奖</Text>
          </View>

          <View className={styles.goodsInfo}>
            <Text>奖品：{baseInfo.content} x{baseInfo.giftNum}</Text>
            <View className={styles.goodsInfo_middle}>
              <Text>价值</Text>
              <Text className={styles.price}>{baseInfo.originalPrice}</Text>
            </View>
          </View>

          <View className={styles.personNum}>
          {lotteryUserList.length > 0 && <View className={styles.lotteryUser} onClick={()=>this.goLotteryUserList()}>
              {lotteryUserList.slice(0,3).map((item, index) => {
                return <Image src={item.avatar} key={index}></Image>
              })}
            </View>}
            <Text>{baseInfo.joinCnt}人已参与</Text>
          </View>

          <View className={styles.detail}>
          <Image onClick={()=>this.goAdsWebView(getAds[2].ads[0].url)} src={getAds.length>0&&getAds[2].ads[0].adImg} mode="widthFix"></Image>
            <Image src={baseInfo.contentImg1} mode="widthFix"></Image>
            <Image src={baseInfo.contentImg2} mode="widthFix"></Image>
            <Image src={baseInfo.contentImg3} mode="widthFix"></Image>
          </View>

          {lotteryDetail.userJoinStatus!=1&&<View className={styles.bottom}><Button className={styles.batton} onClick={()=>{this.join()}} loading={loadingButton} disabled={loadingButton}>{loadingButton?null:`${baseInfo.credits}米粒参加`}</Button></View>
          }



        </View>
        <JoinDialog isOpened={isOpened} onCancel={()=>{this.setState({isOpened:false})}}></JoinDialog>

        <WinDialog isOpened={winDialog} onCancel={() => { this.setState({ winDialog: false }) }}></WinDialog>

          {isLottery&&<Image src={icon_close} className={styles.close} onClick={()=>this.setState({isLottery: false})}></Image>}
        <AtFloatLayout isOpened={isLottery} onClose={this.handleClose.bind(this)} >

          <View className={styles.content}>
            {lotteryDetail.winUsers && lotteryDetail.winUsers.map((item, i) => {
              return (index == i && <Fragment key={i} >
                <Image src={img_arc} className={styles.bg_top}></Image>
                <View className={styles.text}>- 中奖用户 -</View>
                <Image src={item.avatar} className={styles.headPhoto}></Image>
                <View className={styles.name}>{item.alias}</View>
              </Fragment>
              )
            })}
            {lotteryDetail.winUsers&&lotteryDetail.winUsers.length>1&&index!=0&&<Image src={icon_left} className={styles.icon_left} onClick={()=>this.setState({index:index-1})}></Image>}
            {lotteryDetail.winUsers&&lotteryDetail.winUsers.length>1&&index<lotteryDetail.winUsers.length-1&&<Image src={icon_right} className={styles.icon_right} onClick={()=>this.setState({index:index+1})}></Image>}

            <button className={styles.line_button} onClick={()=>this.setState({isLottery: false})}>{lotteryDetail.userStatus == 2 ? "恭喜你中奖了！" : "未中奖~加油！再接再厉"}</button>
          </View>
        </AtFloatLayout>
      </Layout>
    )
  }
}
